<template>
  <div class="hello">
  <label style="border:1px solid #000">
    <input type="file" style="display:none" @change="selectFile" ref="fileInput" multiple/>
    本地文件
  </label>
  <audio ref="player" @ended="nextMusic"></audio>
  <ul>
    <li v-for="(item, index) in fileList" :key="index" :class="{'active': activeIndex === index}" @click="playMusic(index)">{{item}}</li>
  </ul>
  <!-- <div class="bigDiv">
    <div class="testDIV"></div>
    <div class="testDIV"></div>
    <div class="testDIV"></div>
  </div> -->
  </div>
</template>

<script>
// 音频控制audio标签播放本地音乐，可循环播放本地文件夹中的音乐
export default {
  data () {
    return {
      fileList: [],
      event: null,
      activeIndex: -1
    }
  },
  methods: {
    selectFile (e) {
      console.log(e.target.files[0])
      let files = e.target.files
      for (const key in files) {
        if (files.hasOwnProperty(key)) {
          const str = files[key].name
          this.fileList.push(str)
        }
      }
      this.event = e
      setTimeout(() => {
        this.musicPlay(this.event.target.files[0])
        this.activeIndex = 0
      }, 1000)
    },
    nextMusic () {
      this.activeIndex++
      if (this.activeIndex > this.fileList.length - 1) {
        this.activeIndex = 0
      }
      this.musicPlay(this.event.target.files[this.activeIndex])
    },
    musicPlay (str) {
      let reader = new FileReader()
      reader.readAsDataURL(str)
      reader.onload = () => {
        this.$refs.player.src = reader.result
        this.$refs.player.play()
      }
    },
    playMusic (val) {
      this.activeIndex = val
      this.musicPlay(this.event.target.files[this.activeIndex])
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.active {
  color: red;
}
.bigDiv {
  width: 1200px;
  display: flex;
  justify-content: space-between;
  .testDIV {
    width: 300px;
    height: 300px;
    border: 1px solid #000;
    &:hover {
      transform: translate(-20px,-20px);
      box-shadow: 0 0 2px 1px red;
    }
  }
}
</style>
